package com.example.wotu;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragBookml.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragBookml#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragBookml extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private View view;
    private SQLiteDatabase sql;
    private int noid,INorUP = 0;
    private String noname;
    private TextView namebook;
    private EditText mlname;
    private EditText mlxl;
    private ArrayList<Integer> bookDataID;
    private ArrayList<String> bookData,bookDataxl;
    private BaseAdapter mAdapter;
    private ListView ml;
    private ImageView mlIns;
    private ImageView BAO;
    private ImageView chapdel;
    private LinearLayout mllayout;
    private Fragment fragCont;
    private FrameLayout ContB;

    public FragBookml() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragBookml.
     */
    // TODO: Rename and change types and number of parameters
    public static FragBookml newInstance(String param1, String param2) {
        FragBookml fragment = new FragBookml();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.frag_bookml, container, false);
        mListener.onNOT_WK(105);
        noid = getArguments().getInt("bookid");
        noname = getArguments().getString("bookname");
        getFindV();
        getBookData();
        hideZJ();
        ONCLICK();
        return view;
    }

    private void getFindV(){
        namebook = (TextView)view.findViewById(R.id.namebook);
        namebook.setText(noname);
        ml = (ListView)view.findViewById(R.id.ml);
        mlname = (EditText)view.findViewById(R.id.mlname);
        mlxl = (EditText)view.findViewById(R.id.mlxl);
        mlIns = (ImageView)view.findViewById(R.id.mlIns);
        BAO = (ImageView)view.findViewById(R.id.BAO);
        chapdel = (ImageView)view.findViewById(R.id.chapdel);
        mllayout = (LinearLayout)view.findViewById(R.id.mllayout);
        ContB = (FrameLayout) view.findViewById(R.id.ContB);
    }
    private void getBookData(){
        getbooks();
        mAdapter = new ArrayAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,bookData);
        ml.setAdapter(mAdapter);
    }
    private void getbooks(){
        bookDataID = new ArrayList<>();
        bookData = new ArrayList<>();
        bookDataxl = new ArrayList<>();
        try{
            sql = new MySQLOpen(getActivity()).getReadableDatabase();
            Cursor cs = sql.rawQuery("select chapterid,chapxl,chapname from chapter where novelid = ? order by chapxl asc",new String[]{String.valueOf(noid)});
            while (cs.moveToNext()){
                bookDataID.add(cs.getInt(0));
                bookDataxl.add(cs.getString(1));
                bookData.add("["+cs.getString(1)+"] "+cs.getString(2));
            }
            cs.close();
            sql.close();
        }catch (Exception e){
            e.printStackTrace();
            sql.close();
        }
    }
    private void hideZJ(){
        mlname.setVisibility(View.GONE);
        mlxl.setVisibility(View.GONE);
        BAO.setVisibility(View.GONE);
        chapdel.setVisibility(View.GONE);
    }
    private void ONCLICK(){
        mlIns.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mlname.getVisibility() == View.GONE){
                    mlname.setVisibility(View.VISIBLE);
                    mlxl.setVisibility(View.VISIBLE);
                    BAO.setVisibility(View.VISIBLE);
                    mlname.setText("");
                    mlxl.setText("");
                    INorUP = 0;
                }else hideZJ();
            }
        });
        BAO.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JIANP();
                if(mlname.getText().toString().trim().length()>0 && Integer.parseInt(mlxl.getText().toString())>0){
                    if(INorUP == 0){
                        if(bookDataxl.contains(mlxl.getText().toString())){
                            Toast.makeText(getActivity(),"章节序列出现重复了！",Toast.LENGTH_SHORT).show();
                        }else{
                            sql = new MySQLOpen(getActivity()).getReadableDatabase();
                            try{
                                ContentValues cvs = new ContentValues();
                                cvs.put("novelid",noid);
                                cvs.put("chapxl",Integer.parseInt(mlxl.getText().toString()));
                                cvs.put("chapname",mlname.getText().toString());
                                long i = sql.insert("chapter",null,cvs);
                                sql.close();
                                if(i > 0){
                                    hideZJ();
                                    getBookData();
                                }else Toast.makeText(getActivity(),"添加章节失败！",Toast.LENGTH_SHORT).show();
                            }catch (Exception e){
                                e.printStackTrace();
                                sql.close();
                            }
                        }
                    }
                    else if(INorUP > 0){
                        sql = new MySQLOpen(getActivity()).getReadableDatabase();
                        try{
                            Cursor cs = sql.rawQuery("select * from chapter where chapterid != ? and chapxl = ?",new String[]{String.valueOf(INorUP),mlxl.getText().toString()});
                            if(cs.moveToFirst()){
                                sql.close();
                                Toast.makeText(getActivity(),"章节序列出现重复了！",Toast.LENGTH_SHORT).show();
                            }else{
                                ContentValues cvs = new ContentValues();
                                cvs.put("chapxl",Integer.parseInt(mlxl.getText().toString()));
                                cvs.put("chapname",mlname.getText().toString());
                                sql.update("chapter",cvs,"chapterid = ?",new String[]{String.valueOf(INorUP)});
                                sql.close();
                                hideZJ();
                                getBookData();
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            Toast.makeText(getActivity(),"修改错误！",Toast.LENGTH_SHORT).show();
                            sql.close();
                        }
                    }
                }else Toast.makeText(getActivity(),"确认好章节序列与章节名称！",Toast.LENGTH_SHORT).show();
            }
        });
        chapdel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sql = new MySQLOpen(getActivity()).getReadableDatabase();
                try{
                    sql.delete("chapter","chapterid = ?",new String[]{String.valueOf(INorUP)});
                    sql.close();
                    hideZJ();
                    getBookData();
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(getActivity(),"删除错误！",Toast.LENGTH_SHORT).show();
                }finally {
                    sql.close();
                }
            }
        });
        ml.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                mlname.setVisibility(View.VISIBLE);
                mlxl.setVisibility(View.VISIBLE);
                BAO.setVisibility(View.VISIBLE);
                chapdel.setVisibility(View.VISIBLE);
                INorUP = 1;
                sql = new MySQLOpen(getActivity()).getReadableDatabase();
                try{
                    Cursor cs = sql.rawQuery("select chapxl,chapname from chapter where chapterid = ?",new String[]{String.valueOf(bookDataID.get(i))});
                    INorUP = bookDataID.get(i);
                    while (cs.moveToNext()){
                        mlxl.setText(cs.getString(0));
                        mlname.setText(cs.getString(1));
                        break;
                    }
                    sql.close();
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(getActivity(),"长按修改错误！",Toast.LENGTH_SHORT).show();
                    sql.close();
                }
                return true;
            }
        });
        ml.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                JIANP();
                mllayout.setVisibility(View.GONE);
                ContB.setVisibility(View.VISIBLE);
                fragCont = new FragBookCont();
                Bundle bu = new Bundle();
                bu.putInt("chid",bookDataID.get(i));
                fragCont.setArguments(bu);
                getChildFragmentManager().beginTransaction().replace(R.id.ContB,fragCont).commitAllowingStateLoss();
            }
        });
    }
    private void JIANP(){
        //键盘问题
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        void onNOT_WK(int wk);
    }
}
